package com.itheima.easy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.easy.constant.AccraditationRecordConstant;
import com.itheima.easy.constant.PendingTasksConstant;
import com.itheima.easy.constant.RetreatConstant;
import com.itheima.easy.dto.CheckInConfigDto;
import com.itheima.easy.dto.ElderDto;
import com.itheima.easy.entity.BedElder;
import com.itheima.easy.entity.CheckIn;
import com.itheima.easy.entity.CheckInConfig;
import com.itheima.easy.entity.User;
import com.itheima.easy.mapper.*;
import com.itheima.easy.service.*;
import com.itheima.easy.utils.UserThreadLocal;
import com.itheima.easy.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CheckInConfigServiceImpl implements CheckInConfigService {

    // 注入CheckInConfigMapper
    @Resource
    private CheckInConfigMapper checkInConfigMapper;

    @Resource
    private ElderService elderService;

    @Resource
    private BedElderMapper bedElderMapper;

    @Resource
    private BedService bedService;

    @Resource
    private DeptPostUserMapper deptPostUserMapper;

    @Autowired
    private PendingTasksService pendingTasksService;

    @Autowired
    private ApplicationsService applicationsService;

    @Autowired
    private CheckInMapper checkInMapper;

    @Resource
    private PendingTasksMapper pendingTasksMapper;


    /**
     * 根据老人ID查询当前入住配置
     * @param elderId 老人ID
     * @return CheckInConfig
     */
    @Override
    public CheckInConfig findCurrentConfigByElderId(Long elderId) {
        return checkInConfigMapper.findCurrentConfigByElderId(elderId);
    }


    /**
     * 入住选择配置
     *
     * @param checkInConfigDto 入住选择配置
     * @return 受影响的行数
     */
    @Transactional
    @Override
    public int checkIn(CheckInConfigDto checkInConfigDto) {
        // 老人
        ElderDto elderDto = new ElderDto();
        elderDto.setId(checkInConfigDto.getElderId());
        elderDto.setStatus(1);
        elderService.updateByPrimaryKeySelective(elderDto);

        // 床位
        BedElder bedElder = new BedElder();
        bedElder.setBedId(checkInConfigDto.getBedId());
        bedElderMapper.insert(bedElder);

        // 入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        BedVo bedById = bedService.getBedById(checkInConfigDto.getBedId());
        checkInConfig.setBedNo(bedById.getBedNumber());

        // 流程状态 操作记录
        CheckIn checkIn = checkInMapper.selectByPrimaryKey(checkInConfigDto.getCheckInId());
        //设置流程状态
        checkIn.setFlowStatus(CheckIn.FlowStatus.CONFIG.getCode());
        checkInMapper.updateByPrimaryKeySelective(checkIn);
        //  操作记录
        //从当前线程中获取用户数据
        String subject = UserThreadLocal.getSubject();
        User user = JSON.parseObject(subject, User.class);
        //修改之前的待办任务状态，为已处理
        pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_FINISHED, user.getId());

        // 法务员工
        //设置下一个审核人
        //找到法务部门编号--->通过编号查询法务中所有的员工（非leader）---->获取第一个人，找到这个人的id,然后查询对应的角色
        List<Long> userIdList = deptPostUserMapper.selectByDeptNo(RetreatConstant.LEGAL_DEPT_CODE);
        Long userId = userIdList.get(0);
        applicationsService.insert(userId, user, checkIn, AccraditationRecordConstant.AUDIT_STATUS_PASS, "同意");

//        //记录操作记录
//        AccraditationRecord accraditationRecord = new AccraditationRecord();
//        accraditationRecord.setApproverId(user.getId());
//        accraditationRecord.setBussniessId(checkIn.getId());
//        accraditationRecord.setCreateTime(LocalDateTime.now());
//        accraditationRecord.setType(AccraditationRecordConstant.RECORD_TYPE_CHECK_IN);
//        accraditationRecord.setOpinion("同意");
//        accraditationRecord.setApproverName(user.getRealName());
//        accraditationRecord.setCurrentStep("发起申请-申请入住");
//        accraditationRecord.setAuditStatus(AccraditationRecordConstant.AUDIT_STATUS_PASS);
//        accraditationRecord.setStepNo(redisTemplate.boundValueOps(RECORD_STEP_NO_PRE + checkIn.getId()).increment());
//        //审核记录，设置下个节点审核人的角色和用户名
//        //查询下一个审核人的姓名和角色
//        List<UserRoleVo> userRoleVoList = userRoleMapper.selectByUserId(userId);
//        //待办任务，下个节点审核人 设置下个操作人--->护理部主管
//        UserRoleVo userRoleVo = userRoleVoList.get(0);
//        accraditationRecord.setNextApprover(userRoleVo.getUserName());
//        List<String> roleNameList = userRoleVoList.stream().map(x -> x.getRoleName()).collect(Collectors.toList());
//        accraditationRecord.setNextApproverRole(StringUtils.join(roleNameList, ","));
//        accraditationRecord.setNextApproverId(userRoleVo.getId());
//        //保存审核（操作）记录
//        accraditationRecordMapper.insert(accraditationRecord);

        //设置待办

        pendingTasksService.insert(userId, checkIn, CheckIn.FlowStatus.SIGN.getCode());
//        PendingTasks pendingTasks = pendingTasksMapper.selectByCodeAndAssinessId(checkIn.getCheckInCode(), userRoleVo.getId());
//        if (pendingTasks != null) {
//            pendingTasksMapper.updateIsHandle(checkIn.getCheckInCode(), PendingTasksConstant.TASK_IS_HANDLE_UNTREATED, userRoleVo.getId());
//        } else {
//            pendingTasks = checkInService.getPendingTasks(checkIn, CheckIn.FlowStatus.SIGN.getCode());
//            pendingTasks.setAssignee(userRoleVo.getUserName());
//            pendingTasks.setAssigneeId(userRoleVo.getId());
//            pendingTasksMapper.insert(pendingTasks);
//        }
        return checkInConfigMapper.insert(checkInConfig);

    }
}

